package com.sql.parser.lineage.utils;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class MySQLMetadataUtils {

    /**
     * 获取MySQL表列元数据信息
     *
     * @param tables 表名列表
     * @return 包含库、表、列信息的列表
     */
    public static List<String[]> getColumnsMetadata(List<String> tables) throws SQLException {

        String url = "jdbc:mysql://192.168.111.24:19030/ads";
        String username = "root";
        String password = "";

        // 连接到MySQL数据库
        Connection conn = DriverManager.getConnection(url, username, password);

        // 获取表的元数据信息
        DatabaseMetaData dbmd = conn.getMetaData();
        List<String[]> metadataList = new ArrayList<>();
        for (String table : tables) {
            String[] tableInfo = table.split("\\.");
            String sql = "SELECT * FROM Information_schema.columns WHERE table_schema = '" + tableInfo[0] + "' AND table_name = '" + tableInfo[1] + "'";
            Statement stmt = conn.createStatement();
            ResultSet rs = stmt.executeQuery(sql);
//            遍历结果集并将元数据信息存储到列表中
            while (rs.next()) {
                String catalog = rs.getString("TABLE_CATALOG");
                String schema = rs.getString("TABLE_SCHEMA");
                String tableName = rs.getString("TABLE_NAME");
                String columnName = rs.getString("COLUMN_NAME");
                String dataType = rs.getString("DATA_TYPE");
                int columnSize = rs.getInt("CHARACTER_MAXIMUM_LENGTH");
                int decimalDigits = rs.getInt("NUMERIC_SCALE");
                int orderNumber = rs.getInt("ORDINAL_POSITION");
                boolean isNullable = rs.getBoolean("IS_NULLABLE");

                // 将元数据信息存储到字符串数组中
                String[] metadata = {catalog, schema, tableName, columnName, dataType, String.valueOf(columnSize), String.valueOf(decimalDigits), String.valueOf(isNullable), String.valueOf(orderNumber)};
                metadataList.add(metadata);
            }

/*            if (table.equals("ads.ads_equ_info_admin_mp_basic_o_a_d")) {
                metadataList = new ArrayList<>();
                String[] metadata = {"", "ads", "ads_equ_info_admin_mp_basic_o_a_d", "idd1", "int", "11", "0", "1"};
                String[] metadata2 = {"", "ads", "ads_equ_info_admin_mp_basic_o_a_d", "idd2", "int", "11", "0", "2"};
                metadataList.add(metadata);
                metadataList.add(metadata2);
            } else if (table.equals("ads.tb2")) {
                String[] metadata = new String[]{"", "ads", "ads_equ_info_admin_mp_basic_o_a_d", "idd2", "varchar", "255", "0", "YES"};
                metadataList.add(metadata);
            }*/
        }

        // 关闭连接并返回结果
//        conn.close();

        return metadataList;
    }
}

